package wssapp

import (
	"gitee.com/captials-team/ubdframe/src/apps"
	"gitee.com/captials-team/ubdframe/src/apps/wssapp/workers"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/wsserver"
	"go.uber.org/dig"
)

type App struct {
	*apps.App

	di   *dig.Container
	Conf *configstc.WebsocketAppConfig

	ApiServer *ApiServer
	Hub       *wsserver.Hub
	WorkerMgr *workers.WorkerMgr
}

func NewApp(di *dig.Container, conf *configstc.WebsocketAppConfig) *App {
	app := &App{
		di:   di,
		Conf: conf,
		App:  apps.NewApp(di, "websocket_app"),
	}

	logger := v1log.NewZapLog("websocket_app", conf.LogPath)

	common.ErrPanic(di.Provide(NewApiServer))

	wsserver.SetMessageSize(2048 * 1000)
	wsserver.SetLogger(logger.CallerSkip(-1))

	common.ErrPanic(di.Provide(wsserver.NewHub))
	common.ErrPanic(di.Provide(workers.NewWorkerMgr))

	common.ErrPanic(di.Invoke(func(api *ApiServer, hub *wsserver.Hub, mgr *workers.WorkerMgr) {
		api.SetWsHandler(hub.ServeHTTP)

		mgr.AddWorker("log", workers.NewLogWorker(di, logger))
		hub.SetWorker(mgr)
	}))

	common.ErrPanic(di.Invoke(func(api *ApiServer, hub *wsserver.Hub, mgr *workers.WorkerMgr) {
		app.WithApiServer(api)
		app.ApiServer = api

		app.WithWorker(hub)
		app.Hub = hub

		app.WorkerMgr = mgr
	}))

	return app
}
